package com.businesscard.system.controller;

import com.businesscard.system.entity.Admin;
import com.businesscard.system.entity.User;
import com.businesscard.system.service.AdminService;
import com.businesscard.system.service.UserService;
import com.businesscard.system.util.CaptchaUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.validation.Valid;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 管理员控制器
 */
@Controller
@RequestMapping("/admin")
public class AdminController {

    @Autowired
    private AdminService adminService;

    @Autowired
    private UserService userService;

    /**
     * 管理员登录页面
     */
    @GetMapping("/login")
    public String loginPage() {
        return "admin/login";
    }

    /**
     * 管理员登录处理
     */
    @PostMapping("/login")
    @ResponseBody
    public Map<String, Object> login(@RequestBody Admin admin, HttpSession session) {
        Map<String, Object> result = new HashMap<>();

        // 验证验证码
        String captcha = (String) session.getAttribute("captcha");
        if (captcha == null || !captcha.equalsIgnoreCase(admin.getCaptcha())) {
            result.put("success", false);
            result.put("message", "验证码错误");
            return result;
        }

        // 验证用户名和密码
        Admin loginAdmin = adminService.login(admin.getUsername(), admin.getPassword());
        if (loginAdmin != null) {
            // 登录成功，保存管理员信息到session
            session.setAttribute("admin", loginAdmin);
            session.removeAttribute("captcha");

            result.put("success", true);
            result.put("message", "登录成功");
            result.put("admin", loginAdmin);
        } else {
            result.put("success", false);
            result.put("message", "用户名或密码错误");
        }

        return result;
    }

    /**
     * 管理员注销
     */
    @GetMapping("/logout")
    public String logout(HttpSession session) {
        session.invalidate();
        return "redirect:/admin/login";
    }

    /**
     * 管理员首页
     */
    @GetMapping("/index")
    public String index(HttpSession session, Model model) {
        Admin admin = (Admin) session.getAttribute("admin");
        if (admin == null) {
            return "redirect:/admin/login";
        }

        // 获取所有用户列表
        List<User> userList = userService.getAllUsers();
        model.addAttribute("userList", userList);

        return "admin/index";
    }

    /**
     * 用户管理页面
     */
    @GetMapping("/user-management")
    public String userManagement(Model model) {
        try {
            List<User> userList = userService.getAllUsers();
            model.addAttribute("userList", userList != null ? userList : Collections.emptyList());
            return "admin/user-management";
        } catch (Exception e) {
            // 记录错误日志
            e.printStackTrace();
            // 添加错误消息
            model.addAttribute("errorMessage", "获取用户列表失败：" + e.getMessage());
            // 返回空列表
            model.addAttribute("userList", Collections.emptyList());
            return "admin/user-management";
        }
    }

    /**
     * 锁定/解锁用户
     */
    @PostMapping("/lock-user")
    @ResponseBody
    public Map<String, Object> lockUser(@RequestParam Integer userId, @RequestParam Boolean locked, HttpSession session) {
        Map<String, Object> result = new HashMap<>();

        Admin admin = (Admin) session.getAttribute("admin");
        if (admin == null) {
            result.put("success", false);
            result.put("message", "管理员未登录");
            return result;
        }

        boolean success = userService.updateLockStatus(userId, locked);
        if (success) {
            result.put("success", true);
            result.put("message", locked ? "用户已锁定" : "用户已解锁");
        } else {
            result.put("success", false);
            result.put("message", "操作失败");
        }

        return result;
    }

    /**
     * 重置用户密码
     */
    @PostMapping("/reset-password")
    @ResponseBody
    public Map<String, Object> resetPassword(@RequestParam String email, HttpSession session) {
        Map<String, Object> result = new HashMap<>();

        Admin admin = (Admin) session.getAttribute("admin");
        if (admin == null) {
            result.put("success", false);
            result.put("message", "管理员未登录");
            return result;
        }

        boolean success = userService.resetPassword(email);
        if (success) {
            result.put("success", true);
            result.put("message", "密码重置成功，临时密码已发送到用户邮箱");
        } else {
            result.put("success", false);
            result.put("message", "密码重置失败，邮箱不存在");
        }

        return result;
    }

    /**
     * 提升用户为管理员
     */
    @PostMapping("/promote-user")
    @ResponseBody
    public Map<String, Object> promoteUser(@RequestParam Integer userId, HttpSession session) {
        Map<String, Object> result = new HashMap<>();

        Admin admin = (Admin) session.getAttribute("admin");
        if (admin == null) {
            result.put("success", false);
            result.put("message", "管理员未登录");
            return result;
        }

        boolean success = adminService.promoteUserToAdmin(userId);
        if (success) {
            result.put("success", true);
            result.put("message", "用户已提升为管理员");
        } else {
            result.put("success", false);
            result.put("message", "操作失败");
        }

        return result;
    }

    /**
     * 修改密码页面
     */
    @GetMapping("/change-password")
    public String changePasswordPage(HttpSession session) {
        Admin admin = (Admin) session.getAttribute("admin");
        if (admin == null) {
            return "redirect:/admin/login";
        }
        return "admin/change-password";
    }

    /**
     * 修改密码处理
     */
    @PostMapping("/change-password")
    @ResponseBody
    public Map<String, Object> changePassword(@RequestParam String oldPassword, @RequestParam String newPassword,
                                             @RequestParam String confirmPassword, HttpSession session) {
        Map<String, Object> result = new HashMap<>();

        Admin admin = (Admin) session.getAttribute("admin");
        if (admin == null) {
            result.put("success", false);
            result.put("message", "管理员未登录");
            return result;
        }

        // 验证两次密码是否一致
        if (!newPassword.equals(confirmPassword)) {
            result.put("success", false);
            result.put("message", "两次密码不一致");
            return result;
        }

        // 修改密码
        boolean success = adminService.changePassword(admin.getId(), oldPassword, newPassword);
        if (success) {
            result.put("success", true);
            result.put("message", "密码修改成功");
            // 修改成功后退出登录
            session.invalidate();
        } else {
            result.put("success", false);
            result.put("message", "旧密码错误");
        }

        return result;
    }

    /**
     * 验证码生成
     */
    @GetMapping("/captcha")
    public void captcha(HttpServletRequest request, HttpServletResponse response, HttpSession session) {
        // 生成验证码
        String captcha = CaptchaUtil.generateCaptcha(request, response);
        // 保存到session
        session.setAttribute("captcha", captcha);
    }
}

